package com.herench.bs.transfer;

import com.herench.bs.transfer.Dialect;
import com.herench.bs.utils.DataFormatUtils;
import org.apache.cxf.endpoint.Client;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.*;

/**
 * cleverClinic
 * com.herench.bs.transfer.transfer
 *
 * @author wangwenkai
 * @date 2017/10/31/16:50
 */
public class LoadClinicChargeListTransfer extends AbstractTransfer {


    public LoadClinicChargeListTransfer(String method, Client client,String messageMethod) {
        super(method, client,messageMethod);
    }

    @Override
    public String toInvokeMessage(Map<String, Object> params) throws Exception {
        String idCard = (String) params.get("idCard");
        String patientId = (String) params.get("patientId");
        String appointDate = DataFormatUtils.getSimpleTimeString((Date) params.get("appointDate"));
        String tranNo = (String) params.get("tranNo");
        String visitNo = (String) params.get("visitNo");
        Document tplDoc = getTplDoc(getMethod());
        Element dataRowElement = tplDoc.getRootElement().element("CommitData").addElement("Data").addElement("DataRow");
        dataRowElement.addAttribute("PERSON_NO", idCard).addAttribute("PATIENT_ID", patientId).addAttribute("VISIT_NO", visitNo).addAttribute("VISIT_DATE", appointDate).addAttribute("TRAN_NO", tranNo);
        return tplDoc.asXML();
    }

    @Override
    public Map<String, Object> toResultMessage(String resMsg) throws Exception {
        Map<String, Object> res = new HashMap<>(16);
        Document document = DocumentHelper.parseText(resMsg);
        Element resultInfo = document.getRootElement().element("Result").element("Info");
        String executeStatus = resultInfo.attributeValue("EXECUTE_STATUS");
        String executeMessage = resultInfo.attributeValue("EXECUTE_MESSAGE");
        List<Map<String, Object>> appNoList = new ArrayList<>();
        if (Dialect.getSuccessfulState().equals(executeStatus)) {
            List<Element> dataRow = document.getRootElement().element("ReturnData").element("Data").elements();
            for (Element element : dataRow) {
                LoadClinicChargeListInnerMessage innerMassaage = new LoadClinicChargeListInnerMessage(element);
                //flage=0;无重复处方号appNo
                String flag = "0";
                for (Map<String, Object> subMap : appNoList) {

                    if (subMap.get("paySeq").equals(innerMassaage.getAppNo())) {
                        double getTotalCost = Double.parseDouble((String) subMap.get("totalCost"));
                        double innerTotalCost = Double.parseDouble(innerMassaage.getCharges());
                        String totalCost = DataFormatUtils.getFormatMoney(getTotalCost + innerTotalCost);
                        String costTypeName = (String) subMap.get("costTypeName");
                        String costTypeNameList[] = costTypeName.split("\\+");
                        //0:没有重复的项目名
                        String ifIncluded = "0";
                        for (int i = 0; i < costTypeNameList.length; i++) {
                            if (costTypeNameList[i].equals(innerMassaage.getReqClass())) {
                                //1:有重复的项目名
                                ifIncluded = "1";
                            }
                        }
                        if ("0".equals(ifIncluded)) {
                            subMap.put("costTypeName", costTypeName + "+" + innerMassaage.getReqClass());
                        }
                        subMap.put("totalCost", totalCost);
                        subMap.put("inputDateTime", innerMassaage.getInputDateTime());
                        //flage=0;有重复处方号appNo
                        flag = "1";
                    }
                }
                if ("0".equals(flag)) {
                    Map<String, Object> subAppNoMap = new HashMap<>(16);
                    subAppNoMap.put("paySeq", innerMassaage.getAppNo());
                    subAppNoMap.put("totalCost", innerMassaage.getCharges());
                    subAppNoMap.put("costTypeName", innerMassaage.getReqClass());
                    subAppNoMap.put("inputDateTime", innerMassaage.getInputDateTime());
                    appNoList.add(subAppNoMap);
                }

            }

            //按照“inputDateTime”降序排序
            Collections.sort(appNoList, new Comparator<Map<String, Object>>() {
                @Override
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    Date a = null;
                    Date b = null;
                    try {
                        a = DataFormatUtils.parser((String) o1.get("inputDateTime"));
                        b = DataFormatUtils.parser((String) o2.get("inputDateTime"));
                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("LoadClinicChargeListTransfer>>>toResultMessage>>>compare:inputDateTime日期格式转换失败！");
                    }
                    int compareRes = a.compareTo(b);
                    return (compareRes < 0 ? 1 : (compareRes < 1 ? 0 : -1));
                }
            });
            res.put("appNoList", appNoList);
            res.put("code", executeStatus);
            res.put("message", executeMessage);
        }
        return res;
    }

    public class LoadClinicChargeListInnerMessage implements InnerMessage {
        /**
         * 开单项目序号
         */
        private String clinicCostItemNo;
        /**
         * 患者ID
         */
        private String patientId;
        /**
         * 项目编码
         */
        private String itemCode;
        /**
         * 项目名称
         */
        private String itemName;
        /**
         * 项目规格
         */
        private String itemSpec;
        /**
         * 数量
         */
        private String amount;
        /**
         * 单位
         */
        private String units;
        /**
         * 开单科室代码
         */
        private String orderedBy;
        /**
         * 开单医师姓名
         */
        private String orderedDoctor;
        /**
         * 应收费用
         */
        private String costs;
        /**
         * 实收费用
         */
        private String charges;
        /**
         * 医嘱开立时间
         */
        private String inputDateTime;
        /**
         * 开单类别
         */
        private String reqClass;
        /**
         * 开单识别号
         */
        private String reqId;
        /**
         * 用法
         */
        private String admin;
        /**
         * 处方号
         */
        private String appNo;
        /**
         * 就诊ID，就诊日期YYYYMMDD+就诊号
         */
        private String clinicId;
        /**
         * 执行科室代码
         */
        private String performedBy;
        /**
         * 执行科室名称
         */
        private String deptName;
        /**
         * 检验检查大类名称
         */
        private String parentName;
        /**
         * 医生医保分单类型
         */
        private String docInsurType;


        public String getClinicCostItemNo() {
            return clinicCostItemNo;
        }

        public String getPatientId() {
            return patientId;
        }

        public String getItemCode() {
            return itemCode;
        }

        public String getItemName() {
            return itemName;
        }

        public String getItemSpec() {
            return itemSpec;
        }

        public String getAmount() {
            return amount;
        }

        public String getUnits() {
            return units;
        }

        public String getOrderedBy() {
            return orderedBy;
        }

        public String getOrderedDoctor() {
            return orderedDoctor;
        }

        public String getCosts() {
            return costs;
        }

        public String getCharges() {
            return charges;
        }

        public String getInputDateTime() {
            return inputDateTime;
        }

        public String getReqClass() {
            return reqClass;
        }

        public String getReqId() {
            return reqId;
        }

        public String getAdmin() {
            return admin;
        }

        public String getAppNo() {
            return appNo;
        }

        public String getClinicId() {
            return clinicId;
        }

        public String getPerformedBy() {
            return performedBy;
        }

        public String getDeptName() {
            return deptName;
        }

        public String getParentName() {
            return parentName;
        }

        public String getDocInsurType() {
            return docInsurType;
        }

        public LoadClinicChargeListInnerMessage(Element element) {
            this.clinicCostItemNo = element.attributeValue("CLINIC_COST_ITEM_NO");
            this.patientId = element.attributeValue("PATIENT_ID");
            this.itemCode = element.attributeValue("ITEM_CODE");
            this.itemName = element.attributeValue("ITEM_NAME");
            this.itemSpec = element.attributeValue("ITEM_SPEC");
            this.amount = element.attributeValue("AMOUNT");
            this.units = element.attributeValue("UNITS");
            this.orderedBy = element.attributeValue("ORDERED_BY");
            this.orderedDoctor = element.attributeValue("ORDERED_DOCTOR");
            this.costs = element.attributeValue("COSTS");
            this.charges = element.attributeValue("CHARGES");
            this.inputDateTime = element.attributeValue("INPUT_DATE_TIME");
            this.reqClass = element.attributeValue("REQ_CLASS");
            this.reqId = element.attributeValue("REQ_ID");
            this.admin = element.attributeValue("ADMIN");
            this.appNo = element.attributeValue("APP_NO");
            this.clinicId = element.attributeValue("CLINIC_ID");
            this.performedBy = element.attributeValue("PERFORMED_BY");
            this.deptName = element.attributeValue("DEPT_NAME");
            this.parentName = element.attributeValue("PARENT_NAME");
            this.docInsurType = element.attributeValue("DOC_INSUR_TYPE");
        }
    }
}
